﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TeenyGrab.Interfaces;
using TeenyGrab.Objects;
using TeenyGrab.Windows;
using System.IO;
using System.Net;
using System.Drawing;
using TeenyGrab.Helpers;
using System.Drawing.Imaging;
using System.Configuration;
using System.Windows;
using TeenyGrab.Serialization;

namespace TeenyGrab.Outputs
{
    [Serializable]
    public class ImgurOutput : IOutput
    {
        public SerializableImageFormat Format { get; set; }
        public bool Configurable { get { return true; } set { } }

        public string Name { get { return "Imgur"; } set { } }

        public string Description { get { return "Uploads image to Imgur.com"; } set { } }

        public ImgurOutput()
        {
        
        }

        private string PostToImgur(Image image, string apiKey)
        {
            byte[] imageData;

            var fileStream = image.ToStream(Format.Format);
            imageData = new byte[fileStream.Length];
            fileStream.Read(imageData, 0, imageData.Length);
            fileStream.Close();

            const int MAX_URI_LENGTH = 32766;
            string base64img = System.Convert.ToBase64String(imageData);
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < base64img.Length; i += MAX_URI_LENGTH)
            {
                sb.Append(Uri.EscapeDataString(base64img.Substring(i, Math.Min(MAX_URI_LENGTH, base64img.Length - i))));
            }

            string uploadRequestString = "image=" + sb.ToString() + "&key=" + apiKey;

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://api.imgur.com/2/upload");
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ServicePoint.Expect100Continue = false;

            StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream());
            streamWriter.Write(uploadRequestString);
            streamWriter.Close();

            WebResponse response = webRequest.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader responseReader = new StreamReader(responseStream);

            var responseString = responseReader.ReadToEnd();
            var start = responseString.IndexOf("<original>");
            var end = responseString.IndexOf("</original>");
            responseString = responseString.Substring(start+10, end - start - 10);

            return responseString;
        }

        public void Configure()
        {
            var config = new ConfigureImgurOutputWindow(this);
            config.ShowDialog();
        }

        public void Put(ImageObject image)
        {
            var url = PostToImgur(image.Image, ConfigurationManager.AppSettings["ImgurKey"]);
            Clipboard.SetText(url);
            var outputWindow = new UrlOutputWindow(url);
            outputWindow.ShowDialog();
        }
    }
}
